package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.mapper.StudentsMapper;
import com.example.homeworkmanagement.pojo.Classes;
import com.example.homeworkmanagement.mapper.ClassesMapper;
import com.example.homeworkmanagement.pojo.Students;
import com.example.homeworkmanagement.service.ClassesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class ClassesServiceImpl extends ServiceImpl<ClassesMapper, Classes> implements ClassesService {
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public ResultVO<List<Classes>> getClassList(Classes classes, int page, int size) {
        QueryWrapper<Classes> queryWrapper = new QueryWrapper<>();

        // 班级id（模糊查询）
        if (classes.getClassId() != null &&!classes.getClassId().isEmpty()) {
            queryWrapper.like("class_id", classes.getClassId());
        }

        // 年级（模糊查询）
        if (classes.getGrade() != null &&!classes.getGrade().isEmpty()) {
            queryWrapper.like("grade", classes.getGrade());
        }

        // 专业（模糊查询）
        if (classes.getMajor() != null &&!classes.getMajor().isEmpty()) {
            queryWrapper.like("major", classes.getMajor());
        }

        // 院系（模糊查询）
        if (classes.getDepartment() != null &&!classes.getDepartment().isEmpty()) {
            queryWrapper.like("department", classes.getDepartment());
        }

        // 班级名字（模糊查询）
        if (classes.getClassName() != null &&!classes.getClassName().isEmpty()) {
            queryWrapper.like("class_name", classes.getClassName());
        }

        // 分页查询（page从1开始，size为每页大小）
        Page<Classes> pageResult = this.page(new Page<>(page, size), queryWrapper);

        List<Classes> list = this.list(queryWrapper);
        int total= list.size();

        // 返回当前页数据列表
        return ResultVO.success("班级列表获取成功", pageResult.getRecords(),total);
    }

    @Override
    public ResultVO<Classes> getClassDetail(String classId) {
        try {
            Classes classes = this.getOne(new QueryWrapper<Classes>().eq("class_id", classId));
            if (classes == null) {
                return ResultVO.fail("班级id不存在");
            }
            return ResultVO.success("班级详情获取成功", classes);
        } catch (Exception e) {
            return ResultVO.fail("获取班级详情时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Classes> addClass(Classes classes) {
        try {
            // 检查班级id是否已存在
            if (this.getOne(new QueryWrapper<Classes>().eq("class_id", classes.getClassId())) != null) {
                return ResultVO.fail("该班级id已存在");
            }

            boolean saveSuccess = this.save(classes);
            if (!saveSuccess) {
                return ResultVO.fail("班级添加失败");
            }
            return ResultVO.success("班级添加成功", classes);
        } catch (Exception e) {
            return ResultVO.fail("添加班级时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Classes> updateClass(Classes classes) {
        try {
            // 检查班级是否存在
            Classes existingClasses = this.getOne(new QueryWrapper<Classes>().eq("class_id", classes.getClassId()));
            if (existingClasses == null) {
                return ResultVO.fail("班级id不存在");
            }

            // 更新字段（只更新非空值且非空字符串）
            String grade = classes.getGrade();
            if (grade != null &&!grade.trim().isEmpty()) {
                existingClasses.setGrade(grade);
            }

            String major = classes.getMajor();
            if (major != null &&!major.trim().isEmpty()) {
                existingClasses.setMajor(major);
            }

            String department = classes.getDepartment();
            if (department != null &&!department.trim().isEmpty()) {
                existingClasses.setDepartment(department);
            }

            String className = classes.getClassName();
            if (className != null &&!className.trim().isEmpty()) {
                existingClasses.setClassName(className);
            }

            boolean updateSuccess = this.updateById(existingClasses);
            if (!updateSuccess) {
                return ResultVO.fail("班级信息更新失败");
            }
            return ResultVO.success("班级信息更新成功", existingClasses);
        } catch (Exception e) {
            // 这里可根据实际情况记录日志，比如使用log.error("更新班级异常", e);
            return ResultVO.fail("更新班级时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Classes> deleteClass(String classId) {
        try {
            // 检查班级是否存在
            Classes existingClass = this.getOne(new QueryWrapper<Classes>().eq("class_id", classId));
            if (existingClass == null) {
                return ResultVO.fail("班级id不存在");
            }

            // 检查班级下是否有学生
            QueryWrapper<Students> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            List<Students> studentsList = studentsMapper.selectList(queryWrapper);

            if (studentsList != null && !studentsList.isEmpty()) { // 修正判断条件
                return ResultVO.fail("该班级下有学生，无法删除");
            }

            boolean deleteSuccess = this.removeById(classId);
            if (!deleteSuccess) {
                return ResultVO.fail("班级删除失败");
            }
            return ResultVO.success("班级删除成功");
        } catch (Exception e) {
            return ResultVO.fail("删除班级时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> getClassIdsByNames(List<String> classNames) {
        try {
            if (classNames == null || classNames.isEmpty()) {
                return ResultVO.fail("班级名称不能为空");
            }
            QueryWrapper<Classes> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("class_name", classNames);
            queryWrapper.select("class_id");
            List<Classes> classList = classesMapper.selectList(queryWrapper);
            List<String> classIds = classList.stream()
                    .map(Classes::getClassId)
                    .collect(Collectors.toList());
            String classes = classIds.toString().replace("[", "").replace("]", "");
            return ResultVO.success("查询成功", classes);
        } catch (Exception e) {
            return ResultVO.fail("获取班级ID时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> getClassNamesByIds(String classIds) {
        try {
            if (classIds == null || classIds.isEmpty()) {
                return ResultVO.fail("班级id不能为空");
            }
            // 1. 分割班级ID列表
            String[] idArray = classIds.split(",");
            if (idArray.length == 0) {
                return ResultVO.fail("班级id不能为空");
            }

            // 2. 查询每个班级ID对应的名称
            List<String> classNames = new ArrayList<>();
            for (String id : idArray) {
                // 假设Class实体有getId()和getClassName()方法
                Classes classEntity = classesMapper.selectById(id.trim());
                if (classEntity != null) {
                    classNames.add(classEntity.getClassName());
                }
            }
            // 3. 拼接班级名称列表
            String result = String.join(",", classNames);
            return ResultVO.success("查询成功", result);
        } catch (Exception e) {
            return ResultVO.fail("获取班级名称时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<String>> getClassIdsByName(String className) {
        try {
            if(className==null && className.trim().isEmpty()){
                return ResultVO.fail("班级名称不可为空");
            }
            QueryWrapper<Classes> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("class_name",className);
            List<Classes> classesList = classesMapper.selectList(queryWrapper);
            List<String> classIds = new ArrayList<>() ;
            if(classesList.isEmpty()){
                return ResultVO.fail("有有该班级信息");
            }
            for(Classes classes:classesList){
                classIds.add(classes.getClassId());
            }
//            String result = String.join(",",classIds);
            return ResultVO.success("查询成功",classIds);
        }catch (Exception e){
             return ResultVO.fail("查询时发生异常");
        }
    }
}
